const router = require('@koa/router')()
const { userLogin, userFind, userRegister } = require('../controllers/index.js')
const jwt = require('../utils/jwt.js')

router.prefix('/user')

router.post('/login', async (ctx) => {
    // 从请求体中解析到前端传递的参数，去数据库查询账号密码是否合法
    const { username, password } = ctx.request.body

    try {
        const result = await userLogin(username, password)
        console.log(result);
        if (result.length) { // 找到了
            const data = {
                id: result[0].id,
                nickname: result[0].nickname,
                username: result[0].username
            }
            // 生成Token
            const token = jwt.sign(data)

            ctx.body = {
                code: "800",
                data,
                message: "登录成功",
                token: token
            }
        } else {
            ctx.body = {
                code: "804",
                message: "账号和密码错误",
                data: 'error',
            }
        }
    } catch (err) {
        ctx.body = {
            code: '805',
            err,
            message: '服务器异常'
        }
    }

})

router.post('/register', async (ctx) => {
    const { username, password, nickname } = ctx.request.body
    if(!username || !password || !nickname) {
        ctx.body = {
            code: '801',
            message: '账号密码或昵称不能为空'
        }
    }
    try {
        // 判断账号是否存在
    const findRes = await userFind(username)
    if(findRes.length) { // 账号已存在
        ctx.body = {
            code: '803',
            data: 'error',
            message: '账号已存在'
        }
        return
    }
    // 往数据库里写入
    const res = await userRegister({username,password,nickname})
    console.log(res);
    if(res.affectedRows) {
        ctx.body = {
            code: '800',
            data: 'success',
            message: '注册成功'
        }
    }else {
        ctx.body = {
            code: '804',
            data: 'fail',
            message: '注册失败'
        }
    }
    }catch (err) {
        ctx.body = {
            code: '805',
            data: err,
            message: '服务器异常'
        }
    }
})

module.exports = router
